/*   Copyright (C) 2011 Wolfgang Hankeln, Norma J. Wendel
 *
 *   This file is part of CDinFusion.
 *
 *   CDinFusion is free software: you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public 
 *   License in version 3 (LGPL3) as published by the Free Software
 *   Foundation version 3 of the License.
 *
 *   CDinFusion is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the Lesser General Public
 *   License along with CDinFusion; see the file COPYING. If not,
 *   write to the Free Software Foundation, 59 Temple Place - Suite 330,
 *   Boston, MA 02111-1307, USA or see <http://www.gnu.org/licenses/>.
 *   
 *   If you have any questions, send an email to: megx@mpi-bremen.de.
 */
package org.cdinfusion.filehandling;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.mpi_bremen.mgg.FastaValidator.FastaValidatorCallback;

public class FastaReader implements FastaValidatorCallback {

	private static final Pattern HEADER_PATTERN = Pattern
			.compile("^>(\\S+)\\s*(.*)$");

	private ArrayList<String> plainSeqIDs = new ArrayList<String>();
	private int numberOfSequencesFound = 0;
	private String lastSequenceID = null;

	public void header(final String header) {
		final Matcher matcher = HEADER_PATTERN.matcher(header);
		if (matcher.matches()) {
			this.numberOfSequencesFound++;

			if (this.numberOfSequencesFound > 1000) {
				// here no new String is required as only the id of the last
				// sequence is needed, therefore do not create unnecessary
				// objects and do the conversion later
				this.lastSequenceID = matcher.group(1);
			} else {
				// the new String is required as matcher.group() returns
				// a substring on the original string only which keeps the
				// original string in memory
				this.plainSeqIDs.add(new String(matcher.group(1)));
			}
		}
	}

	public void commentline(final String commentline) {
	}

	public void seqline(final String seqline) {
	}

	public void eof() {
		if (this.numberOfSequencesFound > 1000) {
			// if more than 1000 sequence were uploaded only the first and
			// the last sequence id are required -> create a new list
			final String firstSequenceID = this.plainSeqIDs.get(0);
			this.plainSeqIDs = new ArrayList<String>(2);
			plainSeqIDs.add(firstSequenceID);
			// see header() method why a new String is created
			plainSeqIDs.add(new String(this.lastSequenceID));
		} else {
			this.plainSeqIDs.trimToSize();
		}
	}

	public List<String> returnPlainSeqIDs() {
		return this.plainSeqIDs;
	}

	public int getNumberOfSequences() {
		return this.numberOfSequencesFound;
	}
}